package fun.hijklmn.magic.admin.server.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import fun.hijklmn.magic.admin.common.pojo.Role;
import fun.hijklmn.magic.admin.common.vo.req.RoleReqVO;
import fun.hijklmn.magic.admin.common.vo.resp.RoleRespVO;
import fun.hijklmn.magic.admin.server.service.RoleService;
import fun.hijklmn.magic.common.utils.ResultVOUtil;
import fun.hijklmn.magic.common.vo.resp.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsl
 * @since 2021-06-25
 */
@Api(value = "角色管理后台接口", tags = "角色服务前端控制器")
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @ApiOperation(value = "根据条件查询角色列表", tags = "角色服务前端控制器")
    @GetMapping("list")
    public ResultVO list(RoleReqVO roleReqVO) {

        QueryWrapper<Role> queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_delete", 0);

        if (StringUtils.isNotEmpty(roleReqVO.getCode())) {
            queryWrapper.eq("code", roleReqVO.getCode());
        }
        if (StringUtils.isNotEmpty(roleReqVO.getName())) {
            queryWrapper.eq("name", roleReqVO.getName());
        }
        if (roleReqVO.getStatus() != null) {
            queryWrapper.eq("status", roleReqVO.getStatus());
        }

        queryWrapper.orderByDesc("create_time");

        List<Role> roleList = roleService.list(queryWrapper);
        List<RoleRespVO> roleRespVOList = Lists.newArrayList();
        roleList.stream().forEach(role -> {
            RoleRespVO roleRespVO = new RoleRespVO();
            BeanUtils.copyProperties(role, roleRespVO);
            roleRespVOList.add(roleRespVO);
        });

        return ResultVOUtil.success(roleRespVOList);

    }

    @ApiOperation(value = "保存角色", tags = "角色服务前端控制器")
    @PostMapping("save")
    public ResultVO<RoleRespVO> save(@RequestBody RoleReqVO roleReqVO) {
        Role role = roleService.save(roleReqVO);
        RoleRespVO roleRespVO = new RoleRespVO();
        BeanUtils.copyProperties(role, roleRespVO);
        return ResultVOUtil.success(roleRespVO);
    }

}

